import React, { useEffect, useState } from "react";
import {
  Text,
  View,
  ScrollView,
  StyleSheet,
  Image,
  Dimensions,
  ActivityIndicator,
  TouchableOpacity,
  RefreshControl,
} from "react-native";
import Swiper from "react-native-swiper";
import axios from "axios";
import { router } from "expo-router";
import Constants from "expo-constants";
import Api from '../Api/api'
export default function Index() {
  const [loading, setLoading] = useState(true); // 加载状态
  const [carousels, setcarousel] = useState([]); // 轮播图数据
  const [ming, setming] = useState([]); // 名师讲堂数据
  const [refreshing, setRefreshing] = useState(false); // 下拉刷新状态
  const [course, setcourse] = useState([]); // 精品课程数据
  const [doctor, setdoctor] = useState([]); // 肿瘤专家数据
  const [isAtBottom, setIsAtBottom] = useState(false); // 是否到达底部
  const [logimg, setlogimg] = useState([
    { id: 1, imgurl: require("../../assets/images/1.png"), title: "热点追踪" },
    { id: 2, imgurl: require("../../assets/images/2.png"), title: "名师讲堂" },
    { id: 3, imgurl: require("../../assets/images/3.png"), title: "精品课程" },
    { id: 4, imgurl: require("../../assets/images/4.png"), title: "肿瘤会议" },
    { id: 5, imgurl: require("../../assets/images/5.png"), title: "病例分享" },
    { id: 6, imgurl: require("../../assets/images/6.png"), title: "热门活动" },
    { id: 7, imgurl: require("../../assets/images/7.png"), title: "肿瘤专家" },
    { id: 8, imgurl: require("../../assets/images/8.png"), title: "学术中心" },
  ]); // 日志图片
  const [error, setError] = useState({
    carousel: false,
    ming: false,
    course: false,
    doctor: false,
  }); // 错误状态
  // 进行路由跳转
  const handpress = (value: string) => {
    if (value === "病例分享") {
      router.push("/YgFile/Meeting");
    } else if (value === "热门活动") {
      router.push("/YgFile/activity");
    } else if (value === "肿瘤专家") {
      router.push("/YgFile/Academic");
    } else if (value === "学术中心") {
      router.push("/YgFile/Oncologist");
    } else if (value === "精品课程") {
      router.push("/YgFile/Excellentclass");
    } else if (value === "肿瘤会议") {
      router.push("/YgFile/TumorHospital");
    } else if (value === "热点追踪") {
      router.push("/zhcFile/hotTrack");
    } else if (value === "名师讲堂") {
      router.push("/zhcFile/lectures");
    }
  };

  // 下拉刷新处理
  const onRefresh = async () => {
    setRefreshing(true);
    await fetchData(); // 重新获取数据
    setRefreshing(false);
  };
  // 获取数据
  const fetchData = async () => {
    setLoading(true);
    await fetchCarouselImages();
    await getMing();
    await getCourse();
    await getDoctor();
    setLoading(false);
  };
  // 获取数据
  useEffect(() => {
    fetchData();
  }, []);

  // 获取轮播图数据
  const fetchCarouselImages = async () => {
    try {
      const data = await Api.get("/yg/carousel");
      setcarousel(data.data.data);
      setError((prev) => ({ ...prev, carousel: false }));
    } catch (error) {
      console.error("轮播图请求错误", error);
      setError((prev) => ({ ...prev, carousel: true }));
    }
  };
  // 获取名师讲堂数据
  const getMing = async () => {
    try {
      const data = await Api.get("/yg/ming");
      setming(data.data.data.slice(0, 2));
      setError((prev) => ({ ...prev, ming: false }));
    } catch (error) {
      console.error("名师讲堂请求错误", error);
      setError((prev) => ({ ...prev, ming: true }));
    }
  };
  // 获取精品课程数据
  const getCourse = async () => {
    try {
      const data = await Api.get("/yg/course");
      setcourse(data.data.data.slice(0, 4));
      setError((prev) => ({ ...prev, course: false }));
    } catch (error) {
      console.error("精品课程请求错误", error);
      setError((prev) => ({ ...prev, course: true }));
    }
  };
  // 获取肿瘤专家数据
  const getDoctor = async () => {
    try {
      const data = await Api.get("/yg/expert");
      setdoctor(data.data.data.slice(0, 4));
      setError((prev) => ({ ...prev, doctor: false }));
    } catch (error) {
      console.error("肿瘤专家请求错误", error);
      setError((prev) => ({ ...prev, doctor: true }));
    }
  };
  // 渲染名师讲堂数据
  const renderMing = () => {
    if (error.ming || ming.length === 0) {
      return (
        <View style={styles.errorContainer}>
          <Text>暂无数据</Text>
        </View>
      );
    }
    return (
      <View style={styles.ming}>
        <View
          style={{
            width: "100%",
            height: 30,
            flexDirection: "row",
            justifyContent: "space-between",
            alignItems: "center",
            borderBottomWidth: 1,
            borderBottomColor: "#ccc",
          }}
        >
          <Text style={{ fontSize: 16, fontWeight: "bold", color: "#000" }}>
            名师讲堂
          </Text>
          <Text style={{ fontSize: 14, color: "#ccc", paddingRight: 10 }}>
            更多
          </Text>
        </View>
        <View style={styles.mingContainer}>
          {ming.map((item, index) => (
            <View style={styles.mingItem} key={item._id}>
              <Image style={styles.mingImg} source={{ uri: item.img }} />
              <View>
                <Text>
                  {item.mingname} {item.mingarea}
                </Text>
                <Text>{item.department}</Text>
              </View>
            </View>
          ))}
        </View>
      </View>
    );
  };
  // 轮播图内容渲染
  const renderCarousel = () => {
    if (loading) {
      return (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#007BFF" />
          <Text>Loading...</Text>
        </View>
      );
    }
    if (error.carousel || carousels.length === 0) {
      return (
        <View style={styles.errorContainer}>
          <Text>暂无数据</Text>
        </View>
      );
    }
    return (
      <Swiper
        style={styles.wrapper}
        autoplay={true}
        autoplayTimeout={3}
        loop={true} // 启用循环
        loadMinimal={true} // 提前加载图片
        loadMinimalSize={1} // 最小加载图片数量
        dotStyle={styles.dot}
        activeDotStyle={styles.activeDot}
      >
        {carousels.map((item, index) => (
          <View
            style={styles.slide}
            key={index}
            title={<Text style={styles.title}>{item.carouseltitle}</Text>}
          >
            <Image
              style={styles.slideImage}
              source={{ uri: item.carouselimg }}
            />
          </View>
        ))}
      </Swiper>
    );
  };
  // 每个图标的宽度动态计算
  const itemWidth = Dimensions.get("window").width / 4 - 20;

  // 滚动事件
  const handleScroll = (event: any) => {
    const contentHeight = event.nativeEvent.contentSize.height; // 获取内容高度
    const contentOffsetY = event.nativeEvent.contentOffset.y; // 距离滚动的高度
    const layoutHeight = event.nativeEvent.layoutMeasurement.height; // 能看见的高度
    // 检查用户是否滚动到底部
    if (contentOffsetY + layoutHeight >= contentHeight - 30) {
      setIsAtBottom(true); // 用户滚动到底部
    } else {
      setIsAtBottom(false); // 用户没有到底部
    }
  };

  // 推荐课程
  const Course = () => {
    if (error.course || course.length === 0) {
      return (
        <View style={styles.errorContainer}>
          <Text>暂无数据</Text>
        </View>
      );
    }
    return (
      <View style={styles.course}>
        <View style={styles.courseTitle}>
          <Text style={{ fontSize: 16, fontWeight: "bold", color: "#000" }}>
            推荐课程
          </Text>
          <Text style={{ fontSize: 14, color: "#ccc", paddingRight: 10 }}>
            更多
          </Text>
        </View>
        <View style={styles.courseList}>
          {course.map((item) => (
            <View style={styles.courseItem} key={item._id}>
              <Image
                style={{ width: "100%", height: 100 }}
                source={{ uri: item.courseimg }}
              />
              <View>
                <Text numberOfLines={1} ellipsizeMode="tail">
                  {item.coursetitle}
                </Text>
              </View>
            </View>
          ))}
        </View>
      </View>
    );
  };

  // 肿瘤专家
  const Doctor = () => {
    if (error.doctor || doctor.length === 0) {
      return (
        <View style={styles.errorContainer}>
          <Text>暂无数据</Text>
        </View>
      );
    }
    return (
      <View style={styles.Oncologist}>
        {/* 标题 */}
        <View style={styles.courseTitle}>
          <Text style={{ fontSize: 16, fontWeight: "bold", color: "#000" }}>
            肿瘤专家
          </Text>
          <Text style={{ fontSize: 14, color: "#ccc", paddingRight: 10 }}>
            更多
          </Text>
        </View>
        {/* 水平滑动 */}
        <View style={styles.doctorlist}>
          <ScrollView horizontal={true}>
            {doctor.map((item) => (
              <View style={styles.doctItem}>
                <Image style={styles.doctimg} source={{ uri: item.img }} />
                <View>
                  <Text style={{ textAlign: "center" }}>{item.expertname}</Text>
                  <Text
                    style={{
                      fontSize: 14,
                      color: "#ccc",
                      textAlign: "center",
                    }}
                  >
                    {item.job}
                  </Text>
                </View>
              </View>
            ))}
          </ScrollView>
        </View>
      </View>
    );
  };

  return (
    <View style={styles.container}>
      <ScrollView
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
        }
        onScroll={handleScroll} //监听滚动事件
        scrollEventThrottle={16} //每16毫秒触发一次滚动事件
      >
        {renderCarousel()}
        {/*轮播图渲染*/}
        <View style={styles.main}>
          {logimg.map((item, index) => (
            <View>
              <View
                style={[styles.logimg, { width: itemWidth, height: itemWidth }]}
              >
                <Image style={styles.imgs} source={item.imgurl} />
              </View>
              <TouchableOpacity
                onPress={() => {
                  handpress(item.title);
                }}
              >
                <Text style={{ textAlign: "center" }}>{item.title}</Text>
              </TouchableOpacity>
            </View>
          ))}
        </View>
        {renderMing()} {/*名师讲堂*/}
        {/* 推荐课程 */}
        {Course()}
        {/* 肿瘤专家 */}
        {Doctor()}
        {/* 底部提示 */}
        {isAtBottom && (
          <View style={styles.bottomMessage}>
            <Text style={{ color: "#ccc", fontSize: 14 }}>已经到底部了</Text>
          </View>
        )}
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#F5F5F5",
  },
  wrapper: {
    height: 200,
  },
  slide: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "transparent",
  },
  slideImage: {
    width: Dimensions.get("window").width,
    height: "100%",
    resizeMode: "cover",
  },
  title: {
    width: Dimensions.get("window").width,
    color: "#000",
    fontSize: 16,
    textAlign: "center",
    backgroundColor: "#FFF",
    paddingHorizontal: 8,
    paddingVertical: 4,
    marginLeft: -9,
    borderRadius: 5,
  },
  dot: {
    backgroundColor: "rgba(255, 255, 255, 0.5)",
    width: 8,
    height: 8,
    borderRadius: 4,
    marginHorizontal: 3,
  },
  activeDot: {
    backgroundColor: "#FFF",
    width: 10,
    height: 10,
    borderRadius: 5,
    marginHorizontal: 3,
  },
  main: {
    flexDirection: "row",
    flexWrap: "wrap",
    justifyContent: "space-around",
    alignItems: "center",
    width: Dimensions.get("window").width,
    backgroundColor: "#FFF",
    marginTop: 40,
  },
  loadingContainer: {
    justifyContent: "center",
    alignItems: "center",
    height: 200,
  },
  errorContainer: {
    justifyContent: "center",
    alignItems: "center",
    height: 200,
  },
  logimg: {
    borderRadius: "50%",
    backgroundColor: "#E4E4E4",
    justifyContent: "center",
    alignItems: "center",
    margin: 10,
  },
  imgs: {
    width: 30,
    height: 30,
  },
  ming: {
    width: Dimensions.get("window").width,
    height: 200,
    backgroundColor: "#FFF",
    marginTop: 10,
  },
  mingContainer: {
    width: Dimensions.get("window").width,
    height: 160,
    flexDirection: "row",
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    marginTop: 5,
  },
  mingItem: {
    flexBasis: "48%",
    height: 160,
    backgroundColor: "#FFF",
  },
  mingImg: {
    width: "100%",
    height: 120,
  },
  // 精品课程
  course: {
    width: Dimensions.get("window").width,
    height: 310,
    backgroundColor: "#FFF",
    resizeMode: "cover",
    marginTop: 10,
  },
  // 精品课程的标题
  courseTitle: {
    width: Dimensions.get("window").width,
    height: 40,
    backgroundColor: "#FFF",
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    borderBottomWidth: 1,
    borderBottomColor: "#ccc",
  },
  // 精品课程的列表
  courseList: {
    width: Dimensions.get("window").width,
    height: 260, //包裹盒子高度
    marginTop: 10,
    backgroundColor: "#FFF",
    flexDirection: "row",
    justifyContent: "space-around",
    flexWrap: "wrap",
    alignItems: "center",
  },
  courseItem: {
    width: "48%",
    height: 130,
  },
  // 肿瘤专家模块
  Oncologist: {
    width: Dimensions.get("window").width,
    height: 220,
    backgroundColor: "#FFF",
    marginTop: 10,
  },
  doctorlist: {
    width: Dimensions.get("window").width,
    height: 160,
    backgroundColor: "#FFF",
    marginTop: 10,
  },
  doctItem: {
    width: 120,
    height: 160,
    marginLeft: 10,
    marginRight: 10,
  },
  doctimg: {
    width: 120,
    height: 120,
  },
  bottomMessage: {
    width: Dimensions.get("window").width,
    height: 40,
    backgroundColor: "#F5F5F5",
    justifyContent: "center",
    alignItems: "center",
  },
});
